// pages/settlement/settlement.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId:'',
    isHaveCoupon:false,
    isOnlyCoupon:false,
    id:'',
    order:{},
    countdown:'',
    timer: null
  },

//取消订单
quitList : function (e) {
  let _this=this;
  wx.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: function (sm) {
      if (sm.confirm) {
        _this.updateNewOrder(e.currentTarget.dataset.id,4)
        _this.updateInventory();
        _this.backCoupon();
      } 
    }
  })
},
//处理库存
updateInventory(){
  this.data.order.goodsJson.forEach(good => {
    this.setInventory(good.productId, good.buyNum);
  });
},
//修改库存
setInventory(id,buyNum){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/quitInventory', 
    method: 'POST',
    data: {
      id:id,
      buyNum:buyNum,
    },
    success: function(res) {
      console.log("库存处理成功");
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},
//删除订单
delList : function (e) {
  let _this=this;
  wx.showModal({
    title: '提示',
    content: '确定要删除订单吗？',
    success: function (sm) {
      if (sm.confirm) {
        _this.updateNewOrder(e.currentTarget.dataset.id,9)
      } 
    }
  })
  
},
//确认收货
okList : function (e) {
  let _this=this;
  wx.showModal({
    title: '提示',
    content: '点击确认按钮，将确认收货',
    success: function (sm) {
      if (sm.confirm) {
        _this.updateNewOrder(e.currentTarget.dataset.id,3)
      } 
    }
  })
  
},
//售后
service : function (e) {

},


//修改订单状态
updateNewOrder: function (id,state) {
  console.log(id,state)
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/updateNewOrder', 
    method: 'POST',
    data: {
      orderId:id,
      state:state,
    },
    success: function(res) {
      console.log(325)
      _this.getOrder();
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},
copyBtn: function (e) {
  console.log(1210,e.currentTarget.dataset.id);
  //当前索引
  wx.setClipboardData({
    //准备复制的数据内容
    data: e.currentTarget.dataset.id,
    success: function (res) {
      wx.showToast({
        title: '复制成功',
      });
    }
  });
},
//支付
payOrder: function(event) {
  let openid=wx.getStorageSync('openid')
  let phone=wx.getStorageSync('phone');
  
  let orderId=event.currentTarget.dataset.id
  let text=orderId;
  let total_fee=event.currentTarget.dataset.money
  let _this=this
  wx.request({
    url: app.globalData.onlineUrl+'/wxpay',
    data: {
      Goods:{
        text:text,
        total_fee: total_fee*100,
      },
      openid: openid,
      orderId:orderId,
      phone:phone,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
      console.log(1,res.data.data.data)
      let result=res.data.data.data
      wx.requestPayment({
        timeStamp: result.timeStamp,
        nonceStr: result.nonceStr,
        package: result.package,
        signType: result.signType,
        paySign: result.paySign,
        success: res => {
          // wx.navigateTo({
          //   url: '/pages/state/state?type=1'
          // })
          _this.insertCoupon()
          _this.getOrder()
        },
        fail: res => {
          console.log(3,res)
          // wx.navigateTo({
          //   url: '/pages/state/state?type=2'
          // })
        }
      })
    },
  })
},
backCoupon(){
  if(this.data.order.couponId){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/backCoupon',
      data: {
        phone:wx.getStorageSync('phone'),
        id:_this.data.order.couponId,
      },
      header:{'content-type': 'application/json'},
      method:"POST",
      dataType:"json",
      success: res => {
      }
    })
  }
},
//塞券
insertCoupon: function () {
  let coupons=this.data.order.goodsJson.filter(item => item.iscoupon == 1)
  let _this=this;
  console.log(8866,coupons);
  if(coupons.length!=0){
    coupons.forEach(function(obj) {
      console.log(888,obj)
      for(let a = 1; a<=obj.buyNum;a++){
        _this.sendQuan(obj.productId);
      }
    });
  }
},
//给用户送券
sendQuan(couponId){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/addCouponForUser',
    data: {
      phone:wx.getStorageSync('phone'),
      couponId:couponId,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
    }
  })
},
//退款
payOutOrder: function (event) {
  let _this=this
  wx.showModal({
    title: '提示',
    content: '你正在进行退款操作，是否确认？',
    success: function (sm) {
      if (sm.confirm) {
        let orderId=event.currentTarget.dataset.type
        let money=event.currentTarget.dataset.money
        console.log("orderId",orderId);
        //修改订单状态
        wx.request({
          url: app.globalData.onlineUrl+'/wx_refund',
          data: {
            out_trade_no:orderId,
            money:money
          },
          header:{'content-type': 'application/json'},
          method:"POST",
          dataType:"json",
          success: res => {
            _this.updateNewOrder(orderId,8)
          }
        })
      } 
    }
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(123456,options.id);
    console.log(123456,options.type);
    this.setData({
      id:options.id
    })
    if(options.type==2){
      this.getOrder();
    }
    if(options.type==1){
      this.getOldOrder();
    }
  },
  getOldOrder(){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/getOldOrderById', 
      method: 'POST',
      data: {
        id:_this.data.id
      },
      success: function(res) {
        console.log(1988,res.data.data);
        if(res.data.data.state==2){
          res.data.data.state=3
        }
        _this.setData({
          order:res.data.data,
        })
      },
      fail: function(err) {
      },
      complete: function() {}
    });
  },
  getOrder(){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/getNewOrderById', 
      method: 'POST',
      data: {
        id:_this.data.id
      },
      success: function(res) {
        res.data.data.goodsJson=JSON.parse(res.data.data.goodsJson);
        console.log(898989,res.data.data);
        _this.setData({
          orderId:res.data.data.orderId,
          order:res.data.data,
          isHaveCoupon:res.data.data.goodsJson.some(item => item['iscoupon'] == 1),
          isOnlyCoupon:res.data.data.goodsJson.every(item => item['iscoupon'] === 1 || item['productId'] == 114 || item['productId'] == 115 || item['productId'] == 116 || item['productId'] == 117)
        })
        console.log(1,_this.data.isHaveCoupon);
        console.log(1,_this.data.isOnlyCoupon);
        //启动定时器
        if(_this.data.order.state==0){
          _this.startCountdown(_this.data.order.create_time);
        }
      },
      fail: function(err) {
      },
      complete: function() {}
    });
  },
  startCountdown(createTime) {
    const createTimestamp = new Date(createTime).getTime();
    const endTime = createTimestamp + 600000; // 10分钟
    this.updateCountdown(endTime); // 立即更新一次
    this.setTimer(endTime);
  },
  updateCountdown(endTime) {
    const now = Date.now();
    const remaining = endTime - now;

    if (remaining <= 0) {
      this.handleExpired();
      return;
    }

    const minutes = Math.floor(remaining / 60000);
    const seconds = Math.floor((remaining % 60000) / 1000);
    const format = num => num.toString().padStart(2, '0');
    this.setData({ countdown: `${format(minutes)}分${format(seconds)}秒` });
  },
  setTimer(endTime) {
    this.data.timer = setInterval(() => {
      this.updateCountdown(endTime);
    }, 1000);
  },

  clearTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.data.timer = null;
    }
  },
  handleExpired() {
    this.clearTimer();
    this.setData({ 
      countdown: '已过期'
    });
    this.updateNewOrder(this.data.orderId,4)
    this.updateInventory();
    this.backCoupon();
    this.getOrder();

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onUnload() {
    this.clearTimer();
  },

  onHide() {
    this.clearTimer();
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})